<template>
  <div class="ApiGroup">
    <div class="leftDiv">
      <!-- <div class="apiTitle">接口分组</div> -->
      <!-- <el-input
        v-model="inputQueryApi"
        size="mini"
        placeholder="查询接口"
        style="width:200px; margin: 5px 0 10px 27px;"
      ></el-input>-->
      <el-row style="margin:5px">
        <el-col :span="12" style="text-align:center">
          <el-button size="mini" @click="clickCreateGroup">新增分组</el-button>
        </el-col>
        <el-col :span="12" style="text-align:center">
          <el-button size="mini">快速测试</el-button>
        </el-col>
      </el-row>
      <!-- 文件夹分组展示 -->
      <el-table
        size="mini"
        :data="$store.state.GROUP_LIST"
        :show-header="false"
        align="center"
        style="width:100%"
        ref="groupTableRef"
        @cell-click="clickGroupName"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
        v-loading="listLoading"
        element-loading-text="数据正在加载中"
        element-loading-spinner="el-icon-loading"
        :highlight-current-row="true"
      >
        <!-- 表格扩展 -->
        <el-table-column type="expand">
          <!-- 接口显示 表格 -->
          <template slot-scope="scope">
            <el-row
              ref="apiInfoRow"
              v-for="(item,index) in $store.state.API_LIST"
              :key="index"
              style
            >
              <el-col :span="21">
                <el-button
                  ref="apiRow"
                  v-if="item.group_id===scope.row.id"
                  @click="clickApifunc(item,index)"
                  plain
                  size="mini"
                  style="width:140px;margin:0;border:0;display:flex;"
                >
                  <span
                    class="spanrequest"
                    style="display:inline-block;width:70px;text-align:left"
                  >{{ item.request_type }}</span>
                  <span style="display:inline-block;width:70px;text-align:left">{{ item.api_name }}</span>
                </el-button>
                <!-- <el-button v-else-if="item.group_id===scope.row.id"></el-button> -->
              </el-col>
              <!-- 分组接口下拉菜单 -->
              <el-col :span="3">
                <el-dropdown trigger="click" v-if="item.group_id===scope.row.id">
                  <span class="el-dropdown-link">
                    <i class="el-icon-more"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="clickApiDeletefunc(item)">删除</el-dropdown-item>
                    <!-- <el-dropdown-item>{{scope.row.id}}</el-dropdown-item> -->
                  </el-dropdown-menu>
                </el-dropdown>
                
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="group_name" label="分组" width="150px">
          <template slot-scope="scope">
            <i class="el-icon-folder"></i>
            {{scope.row.group_name}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="50px">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <i class="el-icon-more"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="clickGroupDeletefunc(scope.row)">删除</el-dropdown-item>
                <el-dropdown-item @click.native="clickGroupUpdatefunc(scope.row)">修改</el-dropdown-item>
                <!-- <el-dropdown-item>{{scope.row.id}}</el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 右边布局 -->
    <div class="rightDiv" style>
      <!-- 右边第一行 -->
      <el-row style="margin-bottom:10px">
        <span>当前项目：</span>
        <!-- 当前项目下拉列表 -->
        <el-dropdown trigger="click" @command="dropdownHandleCommand" style="margin-right:50px">
          <span class="el-dropdown-link">
            <template v-if="$store.state.PROJECT_NAME">
              <el-link type="primary">{{ $store.state.PROJECT_NAME }}</el-link>
            </template>
            <template v-else>
              <el-link type="primary">请选择项目</el-link>
            </template>
            <el-link type="primary">
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-link>
          </span>
          <el-dropdown-menu slot="dropdown">
            <!-- command 执行菜单点击事件，传入多个参数需构造字典 -->
            <el-dropdown-item
              v-for="item in this.$store.state.PROJECT_LIST"
              :key="item.id"
              :command="{id:item.id,name:item.name}"
            >{{item.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button size="mini" @click="addTab('新建接口')">新增接口</el-button>
        <el-button size="mini">全局参数</el-button>
        <el-button size="mini">Cookie管理器</el-button>
      </el-row>
      <!-- 自定义标签页 -->
      <template v-if="tabIndex > 0">
        <el-tabs
          v-model="editableTabsValue"
          type="card"
          closable
          @tab-click="clikTabEdita"
          @tab-remove="removeTab"
          style="margin-left:5px;"
        >
          <el-tab-pane
            :key="item.name"
            v-for="(item, index) in editableTabs"
            :label="item.title"
            :name="item.name"
          >
            <!-- <ApiList :api='apiNmae'  @myEvent="handleUpdateApiNmae"></ApiList> -->
            <keep-alive>
              <component :is="item.content"></component>
            </keep-alive>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else>
        <div ref="testDom" style="width:100%;text-align:center;">当前未选择接口，请新增或选择接口！！！</div>
      </template>
    </div>
  </div>
</template>

<script>
import ApiList from "../components/ApiList";
import {
  axiosGetGroup,
  axiosPostGroup,
  axiosPutGroup,
  axiosDeleteGroup,
  axiosGetApi,
  axiosDeleteApiInfo
} from "../api/api";
export default {
  data() {
    return {
      //等待提示
      listLoading: false,
      //接口查询
      inputQueryApi: "",
      expands: [],
      //接口分组表格数据
      apiGroupTableData: [
        // {
        //   group_name: "文件夹",
        //   id: "1",
        //   project_id: ""
        // }
      ],
      //正在编辑的标签页
      editableTabsValue: "0",
      //自定义标签页列表
      editableTabs: [
        // {
        // id:"",
        // title: "Tab 1",
        // name: "1",
        // content: "Tab 1 content"
        // }
      ],
      //打开的标签页数量，打开一个加 1
      tabIndex: 0,
      RouteProjectId: 0
    };
  },
  components: {
    ApiList: ApiList
  },
  created() {
    this.getRouteProjectId();
  },
  //进入 项目分组页面三个路径：项目列表，当前项目，浏览器输入地址，进入项目需设置全局变量
  //进入接口标签页三个路径： 新增接口、选择分组下的接口、选择标签页，须关联正在编辑的页面
  mounted() {
    //根据项目id加载页面，发送ajax获取接口分组列表数据
    // this.stopF5Refresh();
    // beforeunloadHandler();
    this.getHtml();
  },
  methods: {
    //浏览器输入地址，根据项目id加载页面
    getHtml() {
      //提取路径中project/后面的数字，获取对应id,进行当前项目显示
      this.getRouteProjectId();
      if (this.RouteProjectId === 0) {
        //id不存在（未输入id或者首次点击菜单栏进入），则返回项目列表界面。
        this.$message.error("请在项目列表中选择项目");
        this.$router.push("/projectlist");
        return;
      }
      console.log();
      this.projectList = this.$store.state.PROJECT_LIST;
      //判断浏览器输入的id是否在项目列表里，如果在，则将当前项目的id和名称写入全局变量
      for (var i = 0; i < this.projectList.length; i++) {
        if (this.projectList[i].id === this.RouteProjectId) {
          this.$store.state.PROJECT_NAME = this.projectList[i].name;
          this.$store.state.PROJECT_ID = this.projectList[i].id;
          //重置分组和标签页
          this.getApiGroupList();
          return;
        }
      }
      if (this.projectId) {
        //如果id存在(浏览器直接输入id)，但不在项目列表里，则提示
        this.$message.error("该项目不存在，请选择当前项目");
      }
    },
    //获取项目ID
    getRouteProjectId() {
      var regex = /(\d+)/;
      var pathStr = this.$route.path;
      this.RouteProjectId = parseInt(pathStr.match(regex));
    },

    //获取项目所有文件夹及文件
    async getApiGroupList() {
      //开启等待提示
      this.listLoading = true;
      var paramsg = { project_id: this.RouteProjectId };
      //获取分组
      await axiosGetGroup(paramsg)
        .then(res => {
          if (res.status === 200) {
            this.$store.state.GROUP_LIST = res.data;
            //插入未知分组
            // console.log(this.$store.state.GROUP_LIST);
            // this.$store.state.GROUP_LIST.push({group_name:'未知分组',project_id: this.RouteProjectId,id:0})
          } else {
            this.$message.error({
              message: "获取分组列表失败！！！",
              //居中显示
              center: true
            });
          }
        })
        .catch(error => this.$message.error({ message: error }));
      var paramsa = { project_id: this.RouteProjectId };
      //发起请求 获取项目所有接口
      await axiosGetApi(paramsa)
        .then(res => {
          this.listLoading = false;
          if (res.status === 200) {
            //将获取到的列表进行状态保存
            this.$store.state.API_LIST = res.data;
            // console.log(res.data)
          } else {
            this.$message.error({
              message: "获取接口列表失败"
            });
          }
        })
        .catch(error => this.$message.error({ message: error }));
    },
    //新增分组
    clickCreateGroup() {
      this.$prompt("请输入分组名称", "新增", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          var params = {
            group_name: value,
            project_id: this.$store.state.PROJECT_ID
          };
          //发起请求，修改接口信息
          axiosPostGroup(params)
            .then(res => {
              if (res.status === 201) {
                //发送成功更新页面
                this.$store.state.GROUP_LIST.push(res.data);
                this.$message({ message: "新增分组成功", type: "success" });
              } else {
                this.$message.error({
                  message: "新增分组失败！！！",
                  duration: 5000
                });
              }
            })
            .catch(error => this.$message.error({ message: error }));
        })
        .catch(() => {});
    },
    //点击分组下拉列表 删除按钮
    clickGroupDeletefunc(row) {
      this.$confirm(
        "确定删除分组： " +
          row.group_name +
          "<br/>该分组下的所有接口也将被删除，是否继续?",
        "提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          var params = { id: row.id };
          //发起请求，修改接口信息
          axiosDeleteGroup(params)
            .then(res => {
              if (res.status === 204) {
                for (let i in this.$store.state.GROUP_LIST) {
                  if (this.$store.state.GROUP_LIST[i].id === row.id) {
                    this.$store.state.GROUP_LIST.splice(i, 1);
                    break;
                  }
                }
                //发送成功更新页面
                this.$message({ message: "删除分组成功", type: "success" });
              } else {
                this.$message.error({
                  message: "删除分组失败！！！",
                  duration: 5000
                });
              }
            })
            .catch(error => this.$message.error({ message: error }));
        })
        .catch(() => {});
    },
    //点击分组下拉列表 修改按钮
    clickGroupUpdatefunc(row) {
      this.$prompt("请输入分组名称", "修改", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          var params = {
            group_name: value,
            id: row.id,
            project_id: row.project_id
          };
          //发起请求，修改接口信息
          axiosPutGroup(params)
            .then(res => {
              if (res.status === 200) {
                //发送成功更新页面
                row.group_name = res.data.group_name;
                this.$message({ message: "修改分组名称成功", type: "success" });
              } else {
                this.$message.error({
                  message: "修改分组名称失败！！！",
                  duration: 5000
                });
              }
            })
            .catch(error => this.$message.error({ message: error }));
        })
        .catch(() => {});
    },
    //点击接口下拉列表 删除按钮
    clickApiDeletefunc(item) {
      console.log(item);
      this.$confirm(
        "确定删除接口： " +
          item.api_name +
          "<br/>该分组下的所有接口也将被删除，是否继续?",
        "提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          var params = { id: item.id };
          //发起请求，修改接口信息
          axiosDeleteApiInfo(params)
            .then(res => {
              if (res.status === 204) {
                for (let i in this.$store.state.API_LIST) {
                  if (this.$store.state.API_LIST[i].id === item.id) {
                    this.$store.state.API_LIST.splice(i, 1);
                    break;
                  }
                }
                //发送成功更新页面
                this.$message({ message: "删除接口成功", type: "success" });
              } else {
                this.$message.error({
                  message: "删除接口失败！！！",
                  duration: 5000
                });
              }
            })
            .catch(error => this.$message.error({ message: error }));
        })
        .catch(() => {});
    },

    //分组--点击选择接口--执行函数
    clickApifunc(item, index) {
      this.$store.state.API_INFO = item;
      // console.log(this.editableTabs);
      if (this.editableTabs.length > 0) {
        //判断当前接口ID是否在编辑的对象里
        for (var i = 0; i < this.editableTabs.length; i++) {
          if (this.editableTabs[i].id === item.id) {
            //当前接口选中
            this.editableTabsValue = index + 1 + "";
            return;
          }
        }
      }
      //保存当前接口名称为全局参数
      for (var j = 0; j < this.$store.state.GROUP_LIST.length; j++) {
        if (this.$store.state.GROUP_LIST[j].id === item.group_id) {
          this.$store.state.GROUP_NAME = this.$store.state.GROUP_LIST[
            j
          ].group_name;
          break;
        }
      }
      //新建标签页
      this.addTab(item.api_name, item.id);
      // this.apiId = item.id;
      // this.$refs.apiRow[index].$el.style.backgroundColor='#C0C4CC';
      // this.$refs.apiInfoRow[index].$el.style.backgroundColor='#C0C4CC';
    },
    //新增接口按钮  新增标签页
    addTab(targetName, id = "") {
      this.isTabs = true;
      let newTabName = ++this.tabIndex + "";
      this.editableTabs.push({
        id: id,
        title: targetName,
        name: newTabName,
        content: "ApiList"
      });
      this.editableTabsValue = newTabName;

      if (id === "") {
        //点击新增接口没有id，方便后续判断是否post新增
        this.$store.state.GROUP_NAME = this.$store.state.GROUP_LIST[0].group_name;
        this.$store.state.API_INFO = {
          project_id: this.$store.state.PROJECT_ID,
          http_type: "HTTP",
          request_type: "GET"
        };
      }
    },
    //标签页被选中时执行函数
    clikTabEdita(tab, event) {
      this.$store.state.API_NAME = tab.label;
      console.log(tab);
      console.log("改变颜色");
      // this.$refs.groupTableRef.$el.children[1].children[0].children[1].children[0].style.backgroundColor='#C0C4CC';
      // console.log(this.$refs.groupTableRef.$el);
    },
    //删除接口标签页，删除时需保存接口参数
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      // localStorage.setItem(
      //   [EDIT_API_TAB_LIST],
      //   JSON.stringify({ value: this.editableTabs, id: this.projectId })
      // );
    },
    //当前项目：点击切换项目,不会重新加载页面
    dropdownHandleCommand(dict) {
      this.$router.push("/project/" + dict.id);
      //重置当前项目,重新获取分组接口信息
      this.getHtml();
      //保存新建接口
      //标签页重置
      // this.changeProjectClearTab();
      this.editableTabsValue = "0";
      this.tabIndex = 0;
      this.editableTabs = [];
    },
    //行数据的 Key，用来优化 Table 的渲染；
    getRowKeys(row) {
      return row.id;
    },
    //行被点击执行事件
    clickGroupName(row, colum, event) {
      if (colum.label !== "操作") {
        //判断此行在不在展开列表里，将此行添加到expands展开列表
        if (this.expands.includes(row.id)) {
          this.expands = this.expands.filter(val => val !== row.id);
          this.$refs.groupTableRef.toggleRowExpansion(row, false);
        } else {
          this.expands.push(row.id);
          this.$refs.groupTableRef.toggleRowExpansion(row, true);
        }
      }
    },

    stopF5Refresh() {
      //禁止F5按键刷新
      document.onkeydown = function(e) {
        var evt = window.event || e;
        var code = evt.keyCode || evt.which;
        if (code == 116) {
          if (evt.preventDefault) {
            evt.preventDefault();
          } else {
            evt.keyCode = 0;
            evt.returnValue = false;
          }
        }
      };
      //禁止鼠标右键
      document.oncontextmenu = function(e) {
        return false;
      };
      //
    },
    beforeunloadHandler(e) {
      window.addEventListener("beforeunload", e => this.beforeunloadHandler(e));
    }
  }
};
</script>

<style scoped>
.ApiGroup {
  display: flex;
}
.leftDiv {
  width: 250px;
}
.rightDiv {
  width: 100%;
  margin: 0;
  padding: 0;
  margin-top: 5px;
}

.apiTitle {
  padding: 5px;
  text-align: center;
  font-size: 20px;
}
button.el-button {
  border-color: #c0c4cc;
}
</style>